package com.ruoyi.common.config.websockert2;

/**
 * @author Fql18
 * @version 1.0
 * @date 2025-08-19 23:19
 * @description
 */

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/webSocket/{sid}")
public class WebSocketServer implements EnvironmentAware {
	//静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	private static int onlineCount = 0;

	//concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
	private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

	private static Environment globalEnvironment;

	//接收sid
	private String sid="";

	//与某个客户端的连接会话，需要通过它来给客户端发送数据
	private Session session;

	@Autowired
	private Environment environment;

	/**
	 * 连接建立成功调用的方法
	 *
	 * @param session 可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(Session session,@PathParam("sid") String sid) {
		//防止重复连接
		for (WebSocketServer item : webSocketSet) {
			if (item.sid.equals(sid)) {
				webSocketSet.remove(item);
				subOnlineCount();           //在线数减1
				break;
			}
		}

		this.session = session;
		this.environment = globalEnvironment;
		webSocketSet.add(this);     //加入set中
		addOnlineCount();           //在线数加1
		System.out.println("有新用户连接，连接名:"+sid+",当前在线人数为" + getOnlineCount());
		this.sid=sid;

	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		webSocketSet.remove(this);  //从set中删除
		subOnlineCount();           //在线数减1
		System.out.println("连接关闭："+sid+"当前在线人数为" + getOnlineCount());
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		System.out.println("收到来自:"+sid+"的信息:"+message);
//        //群发消息
		for (WebSocketServer item : webSocketSet) {
			try {
				System.out.println("推送消息到:"+sid+"，推送内容:"+message);
				item.sendMessage("服务器返回："+message);
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
		}

	}

	/**
	 * 发生错误时调用
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("发生错误");
		error.printStackTrace();
	}

	/**
	 * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
	 */
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
		//this.session.getAsyncRemote().sendText(message);
	}

	/**
	 * 群发自定义消息
	 * */
	public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
		//log.info("推送消息到窗口"+sid+"，推送内容:"+message);
		System.out.println("推送消息到:"+sid+"，推送内容:"+message);
		for (WebSocketServer item : webSocketSet) {
			try {
				//这里可以设定只推送给这个sid的，为null则全部推送
				if(sid==null||sid.length()==0) {
					item.sendMessage(message);
				}else if(item.sid.equals(sid)){
					item.sendMessage(message);
				}
			} catch (IOException e) {
				continue;
			}
		}
	}

	//推送给指定sid
	public static boolean sendInfoBySid(@PathParam("sid") String sid,String message) throws IOException {
		//log.info("推送消息到窗口"+sid+"，推送内容:"+message);
		boolean result=false;
		if(webSocketSet.size()==0){
			result=false;
		}
		for (WebSocketServer item : webSocketSet) {
			try {
				if(item.sid.equals(sid)){
					item.sendMessage(message);
					System.out.println("推送消息到:"+sid+"，推送内容:"+message);
					result=true;
				}
			} catch (IOException e) {
				continue;
			}
		}
		return result;
	}


	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebSocketServer.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebSocketServer.onlineCount--;
	}

	@Override
	public void setEnvironment(final Environment environment) {
		this.environment = environment;
		if (globalEnvironment == null && environment != null) {
			globalEnvironment = environment;
		}
	}
}

